import React, {Component} from 'react';
import {Image, ImageBackground, View} from 'react-native';

export default class AutoSizingImage extends Component {
  constructor(props) {
    super(props);
    // console.log('image:', props.source);
    if (typeof props.source === 'number') {
      const data = Image.resolveAssetSource(props.source);
      // console.log(data);
      this.state = {width: data.width, height: data.height, layoutWidth: 0};
    } else {
      this.state = {width: 0, height: 0, layoutWidth: 0};
      console.log(props.source);
    }
  }

  onLoad = e => {
    // console.log('加载图片成功:', e.nativeEvent);
    // console.log('state:', this.state);
    if (this.state.width === 0 || this.state.height === 0) {
      const {
        nativeEvent: {source, width, height},
      } = e;
      if (width && height) {
        // console.log('height:', height);
        this.setState({width, height});
      } else {
        // console.log('height:', height);
        this.setState({width: source.width, height: source.height});
      }
    }
    if (this.props.onLoad) {
      this.props.onLoad(e);
    }
  };

  getHeight = () => {
    // console.log('height:', this.state.height, this.state.width);
    if (!this.state.height) {
      return this.props.defaultHeight || 10;
    }
    const ratio = this.state.height / this.state.width;
    return this.state.layoutWidth * ratio;
  };

  render() {
    const height = this.getHeight();
    const {style, width, children, ...otherProps} = this.props;
    return (
      <ImageBackground
        {...otherProps}
        onLoad={this.onLoad}
        onLayout={(e)=>{
          const width = e.nativeEvent.layout.width;
          this.setState({layoutWidth: width});
        }}
        style={{width: width, height, ...style}}>
        {children}
      </ImageBackground>
    );
  }
}
